#!/bin/bash
set -e

# APP_ROOT_PATH="/${NAMESPACE}/app/${APP_NAME}-service"
# CONFIG_FILE_PATH="$APP_ROOT_PATH/conf/config.properties"

# 填充占位符变量
function format()
{
	key="\${$1}";value=$2;filePath=$3;
	echo "未替换   key=$key, value=$value, filePath=$filePath";
	value2=`echo $value | sed 's#\/#\\\/#g'`;
	sed -i 's/'$key'/'$value2'/g' $filePath
	echo "已替换 $key -->  $value2"
}

# 修改IP容器host绑定主机
function host()
{
    HOST_IP=`cat /etc/ip`
    cp /etc/hosts /tmp/hosts
    sed -i '$d' /tmp/hosts
    echo "$HOST_IP  $HOSTNAME" >> /tmp/hosts
    cat /tmp/hosts > /etc/hosts
    cat /etc/hosts
}

# 替换配置文件变量
function replaceVar()
{
    #替换通用参数配置文件
    APP_ROOT_PATH="/usr/local/tomcat/webapps/followuphlw"
    CONFIG_HCN_FILE_PATH="$APP_ROOT_PATH/WEB-INF/classes/editor.properties"
    SPRING_HCN_FILE_PATH="$APP_ROOT_PATH/WEB-INF/classes/spring-cluster-master.xml"

    LOG4J_FILE_PATH="$APP_ROOT_PATH/WEB-INF/classes/log4j2.xml"
    HOST_IP=`ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v 172.17.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"`
    format "HOST_IP" "$HOST_IP" $LOG4J_FILE_PATH

    echo "---------- CONFIG_HCN_FILE_PATH -------$CONFIG_HCN_FILE_PATH---"
    # echo "---------- config file $CONFIG_FILE_PATH ----------"
    echo "---------- replace env ----------"

    format "ZK_SVR" "$ZK_SVR" $CONFIG_HCN_FILE_PATH
    format "ZK_ZKAUTH" "$ZK_ZKAUTH" $CONFIG_HCN_FILE_PATH
    format "ZK_ZKAUTH" "$ZK_ZKAUTH" $SPRING_HCN_FILE_PATH
    format "RPC_SVR" "$RPC_SVR" $CONFIG_HCN_FILE_PATH
    format "BROADCAST_SVR" "$BROADCAST_SVR" $CONFIG_HCN_FILE_PATH
    format "DB_SVR" "$DB_SVR" $CONFIG_HCN_FILE_PATH
    format "DB_USER" "$DB_USER" $CONFIG_HCN_FILE_PATH
    format "DB_PASS" "$DB_PASS" $CONFIG_HCN_FILE_PATH
    format "DB_PORT" "$DB_PORT" $CONFIG_HCN_FILE_PATH
    format "ACCESS_TOKEN" "$ACCESS_TOKEN" $CONFIG_HCN_FILE_PATH
    format "INDEXTREE_URL" "$INDEXTREE_URL" $CONFIG_HCN_FILE_PATH


    echo "---------- replace end ----------end"
}

# 运行Jar服务
function runServer(){
    echo "---------- start server ----------"
    /usr/local/tomcat/bin/catalina.sh run
}
if $HOST_RPC; then
    echo "---------- modify /etc/hosts----------"
     host
fi
 replaceVar
 runServer

